package org.dragonnova.business.web;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;

import org.dragonnova.business.dto.WSResponseDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecorator;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;

@Component
public class WebSocketSessionManagerAdapter extends WebSocketSessionManager {

	private final static Logger LOGGER = LoggerFactory
			.getLogger(WebSocketSessionManager.class);

	private final Multimap<WebSocketSession, String> viewmapper;

	public WebSocketSessionManagerAdapter() {
		super();
		this.viewmapper = Multimaps.synchronizedMultimap(HashMultimap.create());
	}

	public void setViewMapper(WebSocketSession session, String viewName) {
		this.viewmapper.put(session, viewName);
	}

	public void removeViewMapper(WebSocketSession session) {
		this.viewmapper.removeAll(session);
	}

	private boolean isContainViewMapper(WebSocketSession session,
			String viewName) {
		if (!this.viewmapper.containsKey(session)) {
			return false;
		}

		Collection<String> views = getViews(session);
		if (views.contains(viewName)) {
			return true;
		}

		return false;
	}

	private Collection<String> getViews(WebSocketSession session) {
		return viewmapper.get(session);
	}

	/**
	 * 
	 * @description:
	 * @author songxy DateTime 2017年5月31日 下午11:22:26
	 * @param message
	 */
	public void sendAllSession(WebSocketMessage message) throws IOException {
		for (Entry<Integer, ConcurrentWebSocketSessionDecorator> item : getWebSockets()) {
			ConcurrentWebSocketSessionDecorator session = item.getValue();
			try {
				String path = session.getDelegate().getUri().getPath();
				if (session.isOpen()
						&& isContainViewMapper(session.getDelegate(), path)) {
					session.sendMessage(message);
				}
			} catch (IOException e) {
				throw e;
			}
		}
	}

	public TextMessage packData(int type, String descString, Object data) {
		WSResponseDto wsDto = new WSResponseDto(type);
		wsDto.setData(data);
		wsDto.setDesc(descString);
		return new TextMessage(JSON.toJSONString(wsDto));
	}

	public TextMessage packData(int type, String descString,
			Map<String, Object> entries) {
		WSResponseDto wsDto = new WSResponseDto(type);
		wsDto.setDesc(descString);
		JSONObject obj = new JSONObject(entries);
		wsDto.setData(obj);
		return new TextMessage(JSON.toJSONString(wsDto));
	}

	public void close() {
		super.destroy();
	}
}
